<template>
  <div class="login">
    <van-nav-bar title="登录" left-arrow @click-left="goBack"></van-nav-bar>
    <div class="container">
      <div class="login-box">
        <van-form @submit="onSubmit">
          <van-field
            v-model="form.username"
            label="用户名"
            placeholder="请输入用户名"
            :border="false"
            :rules="[{ required: true, message: '请输入用户名' }]"
          />
          <van-field
            v-model="form.password"
            type="password"
            label="密码"
            placeholder="请输入密码"
            :border="false"
            :rules="[{ required: true, message: '请输入密码' }]"
          />
          <div class="btn-group">
            <van-button round block type="info" native-type="submit">
              登录
            </van-button>
          </div>
        </van-form>
        <div class="line">
          <van-divider>或</van-divider>
        </div>
        <div class="register-btn">
          <van-button round block @click="register"> 注册 </van-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: "LoginIndex",
  data() {
    return {
      form: {
        username: "",
        password: "",
      },
    };
  },
  methods: {
    onSubmit() {
      this.$http
        .post("/mock/login", this.form)
        .then((res) => {
          console.log(res);
          if (res.code === 200) {
            localStorage.setItem("token", res.data.token);
            localStorage.setItem("userInfo", JSON.stringify(res.data.userInfo));
            this.$router.push({ name: "HomeIndex" });
            this.$toast("登录成功");
          } else {
            this.$toast(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    goBack() {
      this.$router.push({ name: "HomeIndex" });
    },
    register() {
      this.$router.push({ name: "RegisteredIndex" });
    },
    login() {
      this.$router.push({ name: "LoginIndex" });
    },
  },
};
</script>

<style lang="scss" scoped>
.login {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f7f8fa;

  .container {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 0 16px;
    .login-box {
      background: #fff;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      padding-bottom: 24px;
      border-radius: 10px;
      .van-form {
        background: #fff;
        border-radius: 8px;
        padding: 24px 16px 0;

        .van-field {
          margin-bottom: 16px;
        }
      }
      .line {
        margin: -16px 0;
      }
      .register-btn {
        padding: 0 16px;
      }
    }

    .btn-group {
      margin-top: 16px;
      display: flex;
      flex-direction: column;
      gap: 12px;

      .register-btn {
        color: #1989fa;
        border: 1px solid #1989fa;
        background: #fff;
      }
    }
  }
}
</style>